#!/bin/bash

# libEvent uses absolute paths inside the dylibs on macOS. It's been politely
# suggested they switch to a more standard relative rpath scheme, but so far
# the maintainers are not keen, and instead recommend a post-build
# fix-up step using installnametool, so that's what this script does.
#
# see: https://github.com/libevent/libevent/issues/920

echo "Editing libEvent rpaths in: $1"

pushd $1
names="event|event_core|event_extra"

find -E . -type f -depth 1 \
      -regex "\\./lib($names)"'-([0-9]+\.[0-9]+\.[0-9]+)\.dylib$' | \
while read filename; do
    filename="${filename#./}"      # get rid of the './'

    # extract the version part using sed, yuck
    version=$(printf "%s" "$filename" | sed -Ee 's@.*-([0-9]+\.[0-9]+\.[0-9]+)\.dylib$@\1@')

    echo "Found: '$filename'. Version is: $version"

    install_name_tool -id "@rpath/${filename}" ${filename}

    # change primary and 'core' library references
    # if a reference is not found, it's not touched, so we can apply these each time
    install_name_tool -change "$PWD/libevent_core-$version.dylib" "@rpath/libevent_core-$version.dylib" ${filename}
    install_name_tool -change "$PWD/libevent-$version.dylib" "@rpath/libevent-$version.dylib" ${filename}
done

popd

echo "Done fixing install names for libEvent"
